/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trefliq.EJB.mdb;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.embeddable.EJBContainer;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author Yash
 */
public class MovieFlagReceiver {
    private static EJBContainer ec;
    private Context jndiContext;
    private MessageListener ml;
    
    public MovieFlagReceiver(){
        ec = EJBContainer.createEJBContainer();
        jndiContext = ec.getContext();
    }
    public boolean getMessage(){
        try {
            jndiContext = new InitialContext();
            
            // Looks up the administered objects
            ConnectionFactory connectionFactory = (ConnectionFactory) 
                        jndiContext.lookup("jms/trefliq/ConnectionFactory");
            Queue queue = (Queue) jndiContext.lookup("jms/trefliq/MovieReportQueue");
            
            // Connect to queue to send message
            Connection connection = connectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //TemporaryQueue tempQueue = session.createTemporaryQueue();
            //MessageProducer producer = session.createProducer(queue);
            MessageConsumer consumer = session.createConsumer(queue);
            connection.start();
            
            // Receive message
            ml=new MovieFlag();
            consumer.setMessageListener(ml);
            TextMessage message =  (TextMessage)consumer.receive();
            if (message != null) {
                System.out.println("Message received: " + message.getText());
            }
            else {
                System.out.println("No message received.");                
            }
            
            
            // Clean up
            connection.close();
            
            
        } catch (JMSException ex) {
            Logger.getLogger(MovieFlagSender.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (NamingException ex) {
            Logger.getLogger(MovieFlagSender.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
        finally{ ec.close();}
        return true;
    }
}
